package com.baymax.test.scene.internal

import android.app.Notification
import android.app.Service
import android.content.Intent
import android.os.*
import android.util.Log
import com.baymax.test.scene.R
import com.baymax.test.scene.buildNotification
import com.baymax.test.scene.createNotificationId
import kotlinx.coroutines.*

class BackGround : Service(), CoroutineScope by MainScope() {

    val b = Messenger(object :Handler(Looper.getMainLooper()){
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            Log.d("BackGround", "handleMessage: $msg , ${msg.what} ,${msg.obj}")
            Log.d("BackGround", "handleMessage: ${msg.peekData()?.get("hello")}")
        }
    })
    val id  = createNotificationId()
    var count: Job = Job()

    override fun onBind(intent: Intent?): IBinder {
        return b.binder.apply { println("binder $this") }
    }

    override fun onCreate() {
        super.onCreate()
        Log.d("BackGround", "BackGround :onCreate")
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.d("BackGround", "onStartCommand $startId")
        startForeground(id, buildNotification())
        count = launch {
            repeat(3) {
                startForeground(id, buildNotification(it))
                delay(1000)
            }
            Log.d("BackGround", "repeat end")
            stopSelf(startId)
        }
        return super.onStartCommand(intent, flags, startId)

    }

    override fun onUnbind(intent: Intent?): Boolean {
        return super.onUnbind(intent)
        Log.d("BackGround", "onUnbind $intent")
        Log.d("BackGround", "onUnbind ${intent?.extras}")
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.d("BackGround", "onDestroy: ")
        count.cancel()
    }

    private fun buildNotification(countDown: Int = 60): Notification =
        buildNotification {
            setAutoCancel(true)
                .setContentTitle("倒计时服务正在运行")
                .setContentText("${countDown}s后可以再次发送短信")
                .setVibrate(null)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setAutoCancel(true)
        }

}
